package main

import (
	"database/sql"
	"fmt"
	"strings"
)

func getAllKeyI18Ns(db *sql.DB,
	tableName, keyName string, Type int) (map[uint32]string, error) {
	var strPairs = map[uint32]string{}
	querySQL := fmt.Sprintf(
		"SELECT `t1`.`%s`,`t2`.`stringCN` FROM `%s` AS `t1` "+
			"LEFT JOIN `string_text_list` AS `t2` "+
			"ON ((%d<<24)+`t1`.`%s`)=`t2`.`stringID`",
		keyName, tableName, Type, keyName)
	rows, err := db.Query(querySQL)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var keyValue uint32
		var keyText sql.NullString
		if err := rows.Scan(&keyValue, &keyText); err == nil {
			strPairs[keyValue] = keyText.String
		} else {
			return nil, err
		}
	}
	return strPairs, nil
}

func getI18N(db *sql.DB, Type int, ID uint32) (string, error) {
	var str string
	err := db.QueryRow("SELECT `stringCN` FROM `string_text_list` "+
		"WHERE `stringID`=(?<<24)+?", Type, ID).Scan(&str)
	if err != nil {
		return "", err
	}
	return str, nil
}

func setI18N(tx *sql.Tx, Type int, ID uint32, str string) error {
	_, err := tx.Exec(
		"REPLACE INTO `string_text_list`(`stringID`,`stringCN`) "+
			"VALUES((?<<24)+?,?)", Type, ID, str)
	return err
}

func setI18Ns(tx *sql.Tx, args ...interface{}) error {
	_, err := tx.Exec(
		"REPLACE INTO `string_text_list`(`stringID`,`stringCN`) VALUES"+
			strings.Repeat(",((?<<24)+?,?)", len(args)/3)[1:], args...)
	return err
}

func copyI18N(db *sql.DB, tx *sql.Tx, Type int, srcID, tgtID uint32) error {
	str, err := getI18N(db, Type, srcID)
	if err != nil && err != sql.ErrNoRows {
		return err
	}
	if err == nil {
		err = setI18N(tx, Type, tgtID, str)
		if err != nil {
			return err
		}
	}
	return nil
}

func copyI18Ns(db *sql.DB, tx *sql.Tx, args ...interface{}) error {
	for i, n := 0, len(args); i < n; i += 3 {
		err := copyI18N(db, tx,
			args[i].(int), args[i+1].(uint32), args[i+2].(uint32))
		if err != nil {
			return err
		}
	}
	return nil
}
